package com.zywl.web.controller.sys;

import com.alibaba.fastjson.JSONObject;
import com.zywl.core.beans.Association;
import com.zywl.core.beans.Resource;
import com.zywl.core.beans.Role;
import com.zywl.core.beans.User;
import com.zywl.service.AssociationService;
import com.zywl.service.ResourceService;
import com.zywl.service.RoleService;
import com.zywl.service.UserService;
import com.zywl.utils.models.AjaxResult;
import com.zywl.utils.utils.Constants;
import com.zywl.utils.utils.FaceUtils;
import com.zywl.utils.utils.GenerateCodeUtil;
import com.zywl.utils.utils.enums.LogTypeEnum;
import com.zywl.utils.utils.enums.ResTypeEnum;
import com.zywl.web.controller.base.BaseController;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;

@RestController
@RequestMapping("/")
public class LoginController extends BaseController {
    @Autowired
    private ResourceService resourceService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserService userService;
    @Autowired
    private AssociationService associationService;

    /**
     * 账号密码登录
     *
     * @param request
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/loginIn")
    public AjaxResult loginTo(HttpServletRequest request, String username, String password) {
        AjaxResult ar = new AjaxResult();
        try {
            User user = userService.getUsersByUserName(username);
            if (user != null) {
                if (GenerateCodeUtil.MD5(password).equals(user.getUsrPassword())) {
                    //查询协会状态
                    if(user.getUsrAssociationId() != null){
                        Association association = associationService.getById(user.getUsrAssociationId());
                        if(!"0".equals(association.getAssStt())){
                            ar.error("该协会已被禁用，暂无法登入，请联系相关人员");
                            return ar;
                        }
                    }

                    user.setUsrPassword(null);
                    getDatasToSession(request.getSession(), user);
                    saveLog(request, LogTypeEnum.LOGIN.getKey(), "登录平台-账号密码登录");
                    ar.success(user.getUsrName() + "，欢迎进入平台");
                } else {
                    ar.error("登录失败，您的密码不正确");
                }
            } else {
                ar.error("登录失败，改账户不存在");
            }
        } catch (Exception e) {
            ar.error("登录异常", e);
            logger.error("登录异常", e);
        }
        return ar;
    }

    @PostMapping("/loginOut")
    public AjaxResult loginOut(HttpServletRequest request) {
        AjaxResult ar = new AjaxResult();
        saveLog(request, LogTypeEnum.LOGIN.getKey(), "登出平台");
        request.getSession().removeAttribute(Constants.USER_SESSION_KEY);
        request.getSession().removeAttribute(Constants.ROLE_SESSION_KEY);
        request.getSession().removeAttribute(Constants.DICTIONARY_SESSION_KEY);
        request.getSession().removeAttribute(Constants.COMPARTMENT_SESSION_KEY);
        request.getSession().removeAttribute(Constants.ENUM_SESSION_KEY);
        request.getSession().removeAttribute(Constants.RES_SESSION_KEY_MENU);
        request.getSession().removeAttribute(Constants.RES_SESSION_KEY_BUT);

        request.getSession().removeAttribute("username");//移除用户名
        ar.setInfo("登出成功，正在跳转...");
        return ar;
    }

    private void getDatasToSession(HttpSession session, User user) {
        if (user.getUsrRoleId() != null) {
            try {
                long roleId = user.getUsrRoleId();
                Role role = roleService.getById(roleId);
                if (role != null) {
                    session.setAttribute(Constants.ROLE_SESSION_KEY, role);
                }
            } catch (Exception e) {
                logger.error("获取角色异常", e);
            }
        }
        //异步执行-字典
        asyncMethodUtil.putDictToJson(session);
        //异步执行-枚举类
        asyncMethodUtil.putEnumsDataToJson(session);
        asyncMethodUtil.putAssociationToJson(session,user.getUsrAssociationId());
        try {
            List<Resource> resources = null;
            if("admin".equals(user.getUsrUsername()) || user.getUsrAssociationId() == null){
                resources = resourceService.getListAll("res_order desc");
            }else{
                if(user.getUsrRoleId() == null){
                    resources = resourceService.getAllByAssId(user.getUsrAssociationId());
                }else{
                    resources = resourceService.getResourcesByRoleId(user.getUsrRoleId(), null);
                }
            }
            List<String> pathes_menu = new ArrayList<String>();
            List<String> pathes_but = new ArrayList<String>();
            String path = null;
            String resType = null;
            for (Resource resource : resources) {
                path = resource.getResPath();
                if (StringUtils.isNotEmpty(path)) {
                    resType = resource.getResType();
                    if (ResTypeEnum.MENU.getKey().equals(resType)) {
                        pathes_menu.add(path);
                    } else if (ResTypeEnum.BUTTON.getKey().equals(resType)) {
                        pathes_but.add(path);
                    }
                }
            }
            session.setAttribute(Constants.RES_SESSION_KEY_MENU, pathes_menu);
            session.setAttribute(Constants.RES_SESSION_KEY_BUT, pathes_but);
        } catch (Exception e) {
            logger.error("登录时，获取权限数据异常", e);
        }
        session.setAttribute(Constants.USER_SESSION_KEY, user);
    }

}
